/*
 *
 * Copyright (c) 2021
 * User:Dybala
 * File:RegisterController.java
 * Date:2021/11/13 19:12:13
 */

package com.controller.UserController;

import com.config.myAnnotation.PassToken;
import com.pojo.Message;
import com.service.MailService;
import com.service.RegisterService;
import com.service.redisService;
import com.utils.JwtUtils;
import com.utils.VerificationUtils;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import java.util.Map;

/**
 * 这个类用来注册
 */
@Api(tags="用户注册接口")
@RestController
@RequestMapping("/user")
public class RegisterController {
    @Autowired
    MailService mailService;

    @Autowired
    RegisterService service;

    @Autowired
    redisService redisService;
    /**
     * 这个方法用于注册,因为需要user和验证码，所以这里只能采用map传参
     * @param map 传入的所有参数
     * @return
     */
    @ApiOperation("注册接口")
    @ApiResponses({
            @ApiResponse(code = 200, message = "注册成功"),
            @ApiResponse(code = 400, message = "注册失败")
    })
    @PassToken
    @CrossOrigin
    @PostMapping("/register")
    public ResponseEntity register(@ApiParam(value = "参数信息",required = true)@RequestBody Map<String, String> map){
        String email = map.get("email");

        //获取验证码
        String code = map.get("code");
        boolean verify = VerificationUtils.verify(email, code);

        if(!verify){
            Message msg=new Message();
            msg.setFlag(400);
            msg.setMsg("验证码错误");
            return ResponseEntity.ok(msg);
        }
        //参数传递给业务层，让他去new 对象
        Message msg = service.register(map);
        //如果注册失败
        return ResponseEntity.ok(msg);
    }

    /**
     * 发送邮件。生成验证码，存redis
     * @param models
     * @throws MessagingException
     */
    @ApiOperation("发送验证码接口")
    @PassToken
    @CrossOrigin
    @PostMapping("/code")
    public void sendEmail(@ApiParam(value = "参数信息包含邮箱",required = true)@RequestBody Map<String, String> models) throws MessagingException {
        String email = models.get("email");
        // 获取验证码
        String code=VerificationUtils.generateCode();
        // 把校验信息锁到redis里面
        redisService.set(email,code);
        // 设置10分钟的过期时间
        redisService.expire(email, JwtUtils.EXPIRE_TIME/3);
        // 发送邮件
        mailService.sendSimpleMail(email,"（十分钟内有效）您的验证码",code);
    }
}
